package maldade.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import maldade.configuration.ConfigurationLoader;

/**
 * Servlet context listener that will configure our servlet.
 *  
 * @author rnojiri
 *
 */
public class MaldadeServletContextListener implements ServletContextListener {

    private static final String CONFIG_FILE_PATH_KEY = "config.path";
    
    /**
     * Initilizes our servlet.
     */
    public void contextInitialized(ServletContextEvent ctxEvent) 
    {
        ServletContext ctx = ctxEvent.getServletContext();

        String filePath = ctx.getInitParameter(CONFIG_FILE_PATH_KEY);
        
        if (filePath == null || filePath.length() == 0) 
        {
            ctx.log( "Missing parameter in web.xml: " + CONFIG_FILE_PATH_KEY );
            
            throw new RuntimeException( "Missing parameter in web.xml: " + CONFIG_FILE_PATH_KEY );
        }
        
        try
        {
        	ConfigurationLoader.initialize(filePath);
        }
        catch(Exception e)
        {
        	throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * Destroys the servlet.
     */
    public void contextDestroyed( ServletContextEvent ctxEvent )
    {
    	ConfigurationLoader.destroy();
    }
}
